<template>
  <div class="notification-container">
    <div class="header">
      <h2>会员通知管理</h2>
      <div class="header-actions">
        <el-button @click="sendBatchNotification" type="primary" icon="el-icon-message">批量发送</el-button>
        <el-button @click="refreshData" icon="el-icon-refresh">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-message"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalNotifications || 0 }}</h3>
          <p>总通知数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-view"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.readNotifications || 0 }}</h3>
          <p>已读通知</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-warning"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.unreadNotifications || 0 }}</h3>
          <p>未读通知</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="stat-content">
          <h3>{{ Math.round(stats.readRate || 0) }}%</h3>
          <p>阅读率</p>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="通知类型">
          <el-select v-model="searchForm.notificationType" placeholder="请选择通知类型" clearable>
            <el-option label="等级升级" value="LEVEL_UP"></el-option>
            <el-option label="积分获得" value="POINTS_EARNED"></el-option>
            <el-option label="权益解锁" value="BENEFIT_UNLOCKED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阅读状态">
          <el-select v-model="searchForm.isRead" placeholder="请选择状态" clearable>
            <el-option label="已读" :value="true"></el-option>
            <el-option label="未读" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData" >搜索</el-button>
          <el-button @click="resetSearch" >重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 通知列表 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="userName" label="用户" width="120">
          <template slot-scope="scope">
            <div class="user-info">
              <span>{{ scope.row.userName || scope.row.username }}</span>
              <small>ID: {{ scope.row.userId }}</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="notificationType" label="通知类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getNotificationTypeColor(scope.row.notificationType)">
              {{ getNotificationTypeText(scope.row.notificationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="180">
          <template slot-scope="scope">
            <div class="notification-title">
              <span>{{ scope.row.title }}</span>
              <el-tag v-if="!scope.row.isRead" type="danger" size="mini">未读</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="250">
          <template slot-scope="scope">
            <div class="notification-content">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pointsAmount" label="积分" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.pointsAmount" class="points-amount">
              +{{ scope.row.pointsAmount }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isRead" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isRead ? 'success' : 'warning'">
              {{ scope.row.isRead ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发送时间" width="180">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="readAt" label="阅读时间" width="180">
          <template slot-scope="scope">
            <span v-if="scope.row.readAt">{{ formatDate(scope.row.readAt) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="viewDetail(scope.row)"
              type="text"
              icon="el-icon-view"
            >
              查看
            </el-button>
            <el-button
              v-if="!scope.row.isRead"
              size="mini"
              @click="markAsRead(scope.row)"
              type="text"
              icon="el-icon-check"
            >
              标记已读
            </el-button>
            <el-button
              size="mini"
              @click="deleteNotification(scope.row)"
              type="text"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedNotifications.length > 0">
        <span>已选择 {{ selectedNotifications.length }} 项</span>
        <el-button @click="batchMarkAsRead" type="primary" size="small">批量标记已读</el-button>
        <el-button @click="batchDelete" type="danger" size="small">批量删除</el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 通知详情对话框 -->
    <el-dialog
      title="通知详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      @close="closeDetailDialog"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="通知ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentDetail.userName || currentDetail.username }}</el-descriptions-item>
          <el-descriptions-item label="通知类型">{{ getNotificationTypeText(currentDetail.notificationType) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDetail.isRead ? 'success' : 'warning'">
              {{ currentDetail.isRead ? '已读' : '未读' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标题" :span="2">{{ currentDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">{{ currentDetail.content }}</el-descriptions-item>
          <el-descriptions-item label="积分数量" v-if="currentDetail.pointsAmount">
            <span class="points-amount">+{{ currentDetail.pointsAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="等级变化" v-if="currentDetail.fromLevelName || currentDetail.toLevelName">
            <span v-if="currentDetail.fromLevelName">{{ currentDetail.fromLevelName }}</span>
            <span v-if="currentDetail.fromLevelName && currentDetail.toLevelName"> → </span>
            <span v-if="currentDetail.toLevelName">{{ currentDetail.toLevelName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="发送时间">{{ formatDate(currentDetail.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="阅读时间">
            <span v-if="currentDetail.readAt">{{ formatDate(currentDetail.readAt) }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="currentDetail && !currentDetail.isRead" 
          type="primary" 
          @click="markAsRead(currentDetail)"
        >
          标记已读
        </el-button>
      </div>
    </el-dialog>

    <!-- 批量发送通知对话框 -->
    <el-dialog
      title="批量发送通知"
      :visible.sync="batchDialogVisible"
      width="600px"
    >
      <el-form :model="batchForm" :rules="batchRules" ref="batchForm" label-width="100px">
        <el-form-item label="接收用户" prop="userType">
          <el-radio-group v-model="batchForm.userType">
            <el-radio label="all">全部用户</el-radio>
            <el-radio label="level">指定等级</el-radio>
            <el-radio label="specific">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="会员等级" v-if="batchForm.userType === 'level'">
          <el-select v-model="batchForm.levelIds" multiple placeholder="请选择会员等级">
            <el-option
              v-for="level in memberLevels"
              :key="level.id"
              :label="level.levelName"
              :value="level.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户ID" v-if="batchForm.userType === 'specific'">
          <el-input
            v-model="batchForm.userIds"
            type="textarea"
            :rows="3"
            placeholder="请输入用户ID，多个用逗号分隔"
          />
        </el-form-item>
        
        <el-form-item label="通知类型" prop="notificationType">
          <el-select v-model="batchForm.notificationType" placeholder="请选择通知类型">
            <el-option label="系统通知" value="SYSTEM"></el-option>
            <el-option label="活动通知" value="ACTIVITY"></el-option>
            <el-option label="权益提醒" value="BENEFIT_REMINDER"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="batchForm.title" placeholder="请输入通知标题" />
        </el-form-item>
        
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="batchForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendBatchNotificationConfirm">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MemberNotification',
  data() {
    return {
      request: request,
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      searchForm: {
        userId: '',
        notificationType: '',
        isRead: null
      },
      stats: {},
      selectedNotifications: [],
      detailDialogVisible: false,
      currentDetail: null,
      batchDialogVisible: false,
      batchForm: {
        userType: 'all',
        levelIds: [],
        userIds: '',
        notificationType: 'SYSTEM',
        title: '',
        content: ''
      },
      batchRules: {
        notificationType: [
          { required: true, message: '请选择通知类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入通知标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' }
        ]
      },
      memberLevels: []
    }
  },
  mounted() {
    this.loadData()
    this.loadStats()
    this.loadMemberLevels()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        
        const response = await this.request.get('/api/member/notification/page', { params })
        if (response.code === '200') {
          console.log(response.data)
          this.tableData = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadStats() {
      try {
        const response = await this.request.get('/api/member/notification/stats')
        console.log(response.data)
        if (response.code === '200') {
          this.stats = response.data
        } else {
          // 如果接口不存在，使用本地计算
          const total = this.tableData.length
          const read = this.tableData.filter(n => n.isRead).length
          const unread = total - read
          const readRate = total > 0 ? (read / total) * 100 : 0
          
          this.stats = {
            totalNotifications: total,
            readNotifications: read,
            unreadNotifications: unread,
            readRate: readRate
          }
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 如果接口失败，使用本地计算的统计数据
        const total = this.tableData.length
        const read = this.tableData.filter(n => n.isRead).length
        const unread = total - read
        const readRate = total > 0 ? (read / total) * 100 : 0
        
        this.stats = {
          totalNotifications: total,
          readNotifications: read,
          unreadNotifications: unread,
          readRate: readRate
        }
      }
    },
    
    async loadMemberLevels() {
      try {
        const response = await this.request.get('/api/member/level/active')
        if (response.code === '200') {
          this.memberLevels = response.data
        } else {
          this.$message.error(response.msg || '加载会员等级失败')
        }
      } catch (error) {
        console.error('加载会员等级失败:', error)
      }
    },
    
    searchData() {
      this.currentPage = 1
      this.loadData()
    },
    
    resetSearch() {
      this.searchForm = {
        userId: '',
        notificationType: '',
        isRead: null
      }
      this.currentPage = 1
      this.loadData()
    },
    
    refreshData() {
      this.loadData()
      this.loadStats()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    
    handleSelectionChange(selection) {
      this.selectedNotifications = selection
    },
    
    viewDetail(row) {
      this.currentDetail = row
      this.detailDialogVisible = true
    },
    
    closeDetailDialog() {
      this.currentDetail = null
      this.detailDialogVisible = false
    },
    
    async markAsRead(row) {
      try {
        const response = await this.request.post('/api/member/notification/read', {
          notificationIds: [row.id]
        })
        
        if (response.code === '200') {
          this.$message.success('标记成功')
          this.loadData()
          if (this.detailDialogVisible) {
            this.detailDialogVisible = false
          }
        } else {
          this.$message.error(response.msg || '标记失败')
        }
      } catch (error) {
        console.error('标记失败:', error)
        this.$message.error('标记失败')
      }
    },
    
    async batchMarkAsRead() {
      try {
        const notificationIds = this.selectedNotifications.map(n => n.id)
        const response = await this.request.post('/api/member/notification/read', {
          notificationIds
        })
        
        if (response.code === '200') {
          this.$message.success('批量标记成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '批量标记失败')
        }
      } catch (error) {
        console.error('批量标记失败:', error)
        this.$message.error('批量标记失败')
      }
    },
    
    async deleteNotification(row) {
      try {
        await this.$confirm('确定要删除此通知吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.request.delete(`/api/member/notification/${row.id}`)
        if (response.code === '200') {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    
    async batchDelete() {
      try {
        await this.$confirm(`确定要删除选中的 ${this.selectedNotifications.length} 条通知吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const notificationIds = this.selectedNotifications.map(n => n.id)
        const response = await this.request.post('/api/member/notification/batch-delete', {
          notificationIds
        })
        
        if (response.code === '200') {
          this.$message.success('批量删除成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },
    
    sendBatchNotification() {
      this.batchForm = {
        userType: 'all',
        levelIds: [],
        userIds: '',
        notificationType: 'SYSTEM',
        title: '',
        content: ''
      }
      this.batchDialogVisible = true
    },
    
    async sendBatchNotificationConfirm() {
      try {
        await this.$refs.batchForm.validate()
        
        const response = await this.request.post('/api/member/notification/batch-send', this.batchForm)
        if (response.code === '200') {
          this.$message.success('批量发送成功')
          this.batchDialogVisible = false
          // 重置到第一页并刷新数据
          this.currentPage = 1
          this.loadData()
          this.loadStats()
        } else {
          this.$message.error(response.msg || '发送失败')
        }
      } catch (error) {
        console.error('发送失败:', error)
        this.$message.error('发送失败')
      }
    },
    
    getNotificationTypeText(type) {
      const typeMap = {
        'LEVEL_UP': '等级升级',
        'POINTS_EARNED': '积分获得',
        'BENEFIT_UNLOCKED': '权益解锁',
        'SYSTEM': '系统通知',
        'ACTIVITY': '活动通知',
        'BENEFIT_REMINDER': '权益提醒'
      }
      return typeMap[type] || type
    },
    
    getNotificationTypeColor(type) {
      const colorMap = {
        'LEVEL_UP': 'success',
        'POINTS_EARNED': 'warning',
        'BENEFIT_UNLOCKED': 'primary',
        'SYSTEM': 'info',
        'ACTIVITY': 'danger',
        'BENEFIT_REMINDER': 'warning'
      }
      return colorMap[type] || 'info'
    },
    
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.notification-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-content h3 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.stat-content p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-info small {
  color: #999;
  font-size: 12px;
}

.notification-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-content {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.points-amount {
  color: #67c23a;
  font-weight: bold;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
  padding: 10px;
  background: #f0f9ff;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .batch-actions {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style> 